<template>
  <div>
    <div :style="{ height: windowWidth > 768 ? 'calc(100vh - 43px)' : 'calc(100vh)' }" class="content">
      <div class="chat" id="chat" ref="chat" :style="{
        height: windowWidth > 768 ? 'calc(100vh - 110px)' : 'calc(100vh - 60px)',
      }">
        <div class="AIBox">
          <div class="wenben">
            <div>AI报告分析</div>
            <div class="text" v-if="greetingText">
              <span v-html="greetingText"></span>
            </div>
            <div class="text" v-else>思考中···</div>
          </div>
        </div>

        <div class="AIBox" v-for="(item, index) in question" :key="item">
          <div v-if="userData[index] != userCookie" class="wenben">
            <div class="userBox">
              <div class="text">
                {{ userData[index] }}
              </div>
            </div>
            <div>
              <div>AI报告分析</div>
              <div class="think">
                <span v-if="thinkData[index]" v-html="thinkData[index]" :ref="'text' + index"></span>
                <span v-else :ref="'text' + index">思考中...</span>
              </div>
              <div class="text" v-if="resultData[index]">
                <span v-html="resultData[index]" :ref="'text' + index"></span>
                <div v-if="copyChat[index]" class="operate">
                  <div class="copy" @click="copyText(index)">复制</div>
                </div>
                <div v-else style="display: flex; justify-content: flex-end">
                  <div class="resultText" @click="stopType = true">中断</div>
                </div>
              </div>
              <!-- <div class="text" v-else>思考中···</div> -->
            </div>
          </div>
          <div class="question" v-else>
            <div v-for="item in questionArr" :key="item.id">
              <div class="questionItem" @click="questionSend(item)">
                {{ item.title }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="yuyinBgc" v-if="startType">
        <div class="input">
          <el-input placeholder="" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" v-model="valueYuyin">
          </el-input>
        </div>
        <div v-if="endType && !loading" class="cancellation" @click="retract">取消</div>
        <div v-if="endType && !loading" class="ack" @click="sendInput(valueYuyin)">
          发送
        </div>

        <div class="icon" v-if="!endType">
          <div v-if="loading">
            <i class="el-icon-loading"></i>
            <div style="font-size: 14px; margin-top: 5px">语音识别中</div>
          </div>
          <div v-else>
            <i class="el-icon-headset"></i>
            <div style="font-size: 14px; margin-top: 5px">讲话中</div>
          </div>
        </div>
      </div>

      <div class="textInput">
        <div class="icon">
          <i class="el-icon-chat-dot-round"></i>
        </div>
        <!-- <div class="icon" @click="voiceNew" v-else>
          <i class="el-icon-chat-round"></i>
        </div> -->

        <el-input style="flex: 1" v-if="!voiceType" @keyup.enter.native="sendInput()" placeholder="有什么问题尽管问我"
          v-model="value">
        </el-input>

        <div v-else class="voiceType" @touchstart="handleStartRecording" @touchend="handleStopRecording">
          按住讲话
        </div>

        <div class="iconText">
          <div style="padding: 8px 12px" v-if="!resultType" @click="sendInput()">
            发送
          </div>
          <div v-else class="resultText" @click="stopType = true">中断</div>
        </div>
      </div>

      <div class="zzc" v-if="centerDialogVisible || AiConsultDialogVisible"></div>
    </div>

    <el-dialog :title="areaType ? '温馨提示' : ''" :visible.sync="centerDialogVisible"
      :width="windowWidth > 768 ? '380px' : '80%'" center append-to-body :before-close="Aiclose" :modal="false"
      class="dialogAI" :wrapperClosable="false">
      <div v-if="areaType">
        <div class="text">
          <div>请选择您所在区域，联系您的专属客户经理</div>
        </div>
        <div class="area">
          <div class="areaitem" v-for="item in areaArr" :key="item.id" @click="areaPeople(item)">
            {{ item.name }}
          </div>
        </div>
      </div>
      <div v-else class="areaClick">
        <div>{{ areaClick.area }}的专属客户经理</div>
        <div class="nickname">{{ areaClick.nickname }}</div>
        <div>
          <a :href="`tel:${areaClick.phone}`" class="phone">{{ areaClick.phone }}</a>
        </div>
        <div><a :href="`tel:${areaClick.phone}`" class="btn">立即联系</a></div>
      </div>
    </el-dialog>

    <el-dialog :title="areaType ? '请选择您的问题类型' : ''" :visible.sync="AiConsultDialogVisible"
      :width="windowWidth > 768 ? '380px' : '80%'" center append-to-body :before-close="Aiclose" :modal="false"
      class="dialogAI" :wrapperClosable="false">
      <div v-if="areaType">
        <div class="ConsultItem" v-for="item in AiConsultArr" :key="item.id" @click="Consult(item)">
          {{ item.title }}
        </div>
      </div>
      <div v-else class="areaClick">
        <div class="nickname">{{ areaClick.name }}</div>
        <div>
          <a :href="`tel:${areaClick.mobile}`" class="phone">{{ areaClick.mobile }}</a>
        </div>
        <div><a :href="`tel:${areaClick.mobile}`" class="btn">立即联系</a></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import VueMarkdownEditor, { xss } from "@kangc/v-md-editor";
import MarkdownIt from 'markdown-it';
import { PAGE_BASE_URL } from "@/config";
import { HZRecorder } from "./js/HZRecorder.js";
import axios from "axios";
export default {
  data() {
    return {
      centerDialogVisible: false,
      AiConsultDialogVisible: false,

      resultType: false, //问题回答中
      resultload: "", //问题回答中的文字
      thinkload: "", //思考数据中的文字
      resultData: [], //ai回答数据,
      resultType2: true, //思考数据回答中
      thinkData: [], //思考数据,
      resultBase64: "",
      userData: [], //用户问题数据,

      likeArr: [], //点赞
      areaArr: [], //区域用户
      phoneNumber: "",

      areaType: true,
      areaClick: {},

      copyChat: [],

      question: 0, //问了几个问题

      questionArr: [],
      // url: "https://21428erbx269.vicp.fun/chat", //java
      url: "https://test.ai.oramage.com/web.php/chat/sendText", //阿里
      // url: 'https://wss.lke.cloud.tencent.com/v1/qbot/chat/sse',//腾讯
      value: "",
      valueYuyin: "",
      notYuyin: false,
      chatDom: "",
      isScrollByTouch: false, //判断是否置底

      stopType: false, //中断
      copy: [],

      voiceType: false, //是否语音输入
      audioBuffer: null,

      AiConsultArr: [],

      userCookie: "",

      demoText: "",
      recordedBlobs: [],
      greetingText: "",

      recorder: HZRecorder,
      intervalId: null,
      audio_context: AudioContext,
      index: 0,
      timeCount: 0,
      luyinType: false,

      startType: false, //按住语音
      endType: false, //讲话结束

      errText: [],
      loading: false,
      timer: null,

      windowWidth: window.innerWidth,
    };
  },
  watch: {
    resultload: {
      handler(val) {
        if (this.isScrollByTouch) {
          this.$nextTick(() => {
            this.chatDom.scrollTop = this.chatDom.scrollHeight;
          });
        }
      },
    },
  },
  created() {
    document.title = "AI报告分析";

    this.userCookie = this.getCookie("userCookie");
    console.log(this.userCookie, "开始");
    if (this.userCookie) {
      this.getHistoryMsg();
      this.setExpireCookie("userCookie", this.userCookie, 15);
    } else {
      //设置一个名为"userCookie"的cookie，值为"this.generateRandomCode(10)"，并在15分钟后过期
      let userCookie = this.generateRandomCode(32);
      this.setExpireCookie("userCookie", userCookie, 15);
      this.userCookie = this.getCookie("userCookie");
      this.commonProblem();
    }
    console.log(this.userCookie, "ok");
    this.iniText();


  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
  },
  mounted() {
    window.addEventListener("resize", this.handleResize());
    this.chatDom = this.$refs.chat;

    // 手指移动时的处理
    this.chatDom.addEventListener("touchmove", (e) => {
      let scrollTop = this.chatDom.scrollTop; // 元素卷去高度
      let clientHeight = this.chatDom.clientHeight; // 元素出现高度
      let scrollHeight = this.chatDom.scrollHeight; //元素内容高度的度量
      if (clientHeight + scrollTop === scrollHeight) {
        this.isScrollByTouch = true;
      } else {
        this.isScrollByTouch = false;
      }
    });

    this.chatDom.addEventListener("wheel", (event) => {
      let scrollTop = this.chatDom.scrollTop; // 元素卷去高度
      let clientHeight = this.chatDom.clientHeight; // 元素出现高度
      let scrollHeight = this.chatDom.scrollHeight; //元素内容高度的度量

      // console.log(clientHeight + scrollTop === scrollHeight,'wheel');
      if (clientHeight + scrollTop === scrollHeight) {
        this.isScrollByTouch = true;
      } else {
        this.isScrollByTouch = false;
      }
    });
  },
  methods: {
    countWordOccurrences(str, word) {
      const regex = new RegExp(`\\b${word}\\b`, "g");
      return (str.match(regex) || []).length;
    },
    async Consult(item) {
      console.log(item);
      if (item.type == 1) {
        const response = await axios.post(
          "https://h5.srea.net.cn/api/v1/home/getAiConsultDetail",
          {
            id: item.id,
          }
        );
        console.log(response.data.data);
        this.areaType = false;
        this.areaClick = response.data.data;
        this.areaClick.area = item.name;
      } else {
        this.AiConsultDialogVisible = false;
        this.centerDialogVisible = true;
        this.getAiTips();
      }
    },
    Aiclose() {
      this.centerDialogVisible = false;
      this.AiConsultDialogVisible = false;
      this.areaType = true;
    },
    async areaPeople(item) {
      const response = await axios.post(
        "https://h5.srea.net.cn/api/v1/home/getAiTipDetail",
        {
          area_id: item.id,
        }
      );
      console.log(response.data.data);
      this.areaClick = response.data.data;
      this.areaClick.area = item.name;
      this.areaType = false;
    },
    async like(index, is_zan) {
      const response = await axios.post(
        "https://test.ai.oramage.com/web.php/chat/saveZan",
        {
          user_token: this.userCookie,
          is_zan: is_zan,
          question: this.userData[index],
        }
      );

      this.$set(this.likeArr, index, is_zan);

      console.log(this.likeArr);

      if (is_zan == 2) {
        this.$message({
          message: "感谢您的反馈",
          center: true,
          type: "success",
          offset: window.screen.height / 2,
        });
      } else if (is_zan == 1) {
        this.getAiConsult();
      }
    },
    async getAiConsult() {
      const { data: response2 } = await axios.post(
        "https://h5.srea.net.cn/api/v1/home/getAiConsult",
        {}
      );
      this.AiConsultDialogVisible = true;
      console.log(response2.data);
      this.AiConsultArr = response2.data;
    },
    async getAiTips() {
      const response2 = await axios.post(
        "https://h5.srea.net.cn/api/v1/home/getAiTips",
        {}
      );

      console.log(response2.data.data.area);
      this.areaArr = response2.data.data.area;
      this.phoneNumber = response2.data.data.customer_mobile;
      this.centerDialogVisible = true;
    },
    handleResize() {
      this.windowWidth = window.innerWidth;
    },
    questionSend(item) {
      console.log(item);
      // this.sendInput(item.trigger_problem);
      this.sendInput(item.title);
    },
    async commonProblem() {
      const response = await axios.post(
        "https://test.ai.oramage.com/web.php/chat/commonProblem",
        {
          user_token: this.userCookie,
        }
      );
      console.log(response.data.data, "问题");
      // this.questionArr = response.data.data;
      this.questionArr = [{
        title: '为我总结这份报告'
      }, {
        title: '帮我推荐一家走访企业并说明推荐理由'
      }]



      this.$nextTick(() => {
        this.userData.push(this.userCookie);
        this.likeArr.push(0);
        this.resultData.push(this.userCookie);
        this.$set(this, "question", this.question + 1);
        setTimeout(() => {
          this.chatDom.scrollTop = this.chatDom.scrollHeight;
        }, 0);
      });

      // let itemDiv;
      // this.questionArr.map((res) => {
      //   itemDiv = `
      //   <div
      //     class="questionItem"
      //   >
      //     <div class="title">${res.title}</div>
      //     <div class="text">${res.explanatory}</div>
      //   </div>
      //   `;
      // });
      // let newDiv = document.createElement("div");
      // newDiv.className = "question";
      // newDiv.innerHTML = `
      //   ${itemDiv}
      // `;
      // this.$nextTick(() => {
      //   this.chatDom.append(newDiv);
      // });
    },
    async iniText() {
      const response = await axios.post(
        "https://test.ai.oramage.com/web.php/chat/iniText",
        {
          // 你要发送的数据
          user_token: this.userCookie,
        }
      );
      // this.greetingText = response.data.data.iniText;
      this.greetingText = '您好，我是AI报告分析小助理，关于这份报告相关的所有问题您都可以问我。';
    },
    // 历史数据
    async getHistoryMsg() {
      const response = await axios.post(
        "https://test.ai.oramage.com/web.php/chat/getHistoryMsg",
        {
          // 你要发送的数据
          user_token: this.userCookie,
        }
      );
      let list = response.data.data.list;
      this.question = list.length / 2;

      list.map((res, index) => {
        if ((index + 1) % 2 == 1) {
          this.userData.push(res.message);
        } else {
          // let html = xss.process(
          //   VueMarkdownEditor.themeConfig.markdownParser.render(res.message)
          // );
          this.resultData.push(res.message);
          this.copyChat.push(true);

          this.likeArr.push(0);
        }
      });

      console.log(this.likeArr, "this.likeArr");

      //常见问题
      this.commonProblem();
    },
    getCookie(name) {
      const cookies = document.cookie.split("; ");
      for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].split("=");
        if (cookie[0] === name) {
          return cookie[1];
        }
      }
      return "";
    },
    // 设置一个15分钟过期的cookie

    // setExpireCookie("exampleCookie", "cookieValue", 15);
    setExpireCookie(name, value, minutes) {
      var cookieExp = new Date();
      cookieExp.setMinutes(cookieExp.getMinutes() + minutes);

      var expires = "; expires=" + cookieExp.toUTCString();
      var domain = "; domain=" + window.location.hostname; // 可选，设置cookie的域
      var path = "; path=" + window.location.pathname; // 可选，设置cookie的路径
      var samesite = "; SameSite=Strict"; // 可选，设置cookie的SameSite属性
      document.cookie =
        name + "=" + encodeURIComponent(value) + expires + domain + path + samesite;
    },
    // 随机码
    generateRandomCode(length) {
      var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
      var code = "";
      for (var i = 0; i < length; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return code;
    },
    async postAudioDataToServer(audioBase64) {
      const response = await fetch("https://fang.srea.com.cn/api/upload", {
        headers: {
          "Content-Type": "application/json",
        },
        method: "POST",
        body: JSON.stringify({ file: audioBase64 }),
      });
      console.log(response, "response");
      // const result = await response.json();
      // 在前端页面上展示处理后的语音识别结果
      // showAsrResult(result.result);
    },
    initNew() {
      var that = this;
      this.$nextTick(() => {
        that.recorder.clear();
        navigator.mediaDevices.getUserMedia(
          { audio: true },
          function (stream) {
            that.recorder = new HZRecorder(stream, {
              sampleBits: 16,
              sampleRate: 8000,
            });
            console.log("初始化完成");
          },
          function (e) {
            console.log("No live audio input: " + e);
          }
        );
      });
    },
    async handleStopRecording() {
      clearInterval(this.timer);
      console.log("结束录音");
      // this.startType = false
      this.loading = true;
      if (!this.luyinType) {
        this.$message({
          message: "对不起，录音时间太短",
          offset: window.screen.height / 2,
          center: true,
          type: "warning",
        });
        this.endType = true;
        this.loading = false;
        this.recorder.stop();
        clearInterval(this.intervalId);
        this.retract();
        this.initNew();
        return;
      }
      setTimeout(() => {
        this.recorder.stop();
        clearInterval(this.intervalId);
        axios
          .post("https://api.aitext.oramage.com/asr", { data: this.resultBase64 })
          .then((res) => {
            console.log(res.data.data);
            if (!res.data.data) {
              this.$message({
                message: "未识别出语音",
                center: true,
                type: "warning",
                offset: window.screen.height / 2,
              });
              this.retract();
            }
            this.valueYuyin = res.data.data;
            this.errText.push(res.data);
            this.endType = true;
            this.loading = false;
            this.initNew();
          })
          .catch((error) => {
            this.errText.push("error");
          });
      }, 500);

      return;
    },
    // blob 转 base64
    blobToDataURI(blob, callback) {
      var reader = new FileReader();
      reader.readAsDataURL(blob);
      reader.onload = function (e) {
        callback(e.target.result);
      };
    },
    handleStartRecording() {
      // 开始录制音频
      // this.stopType = true;
      this.startType = true;

      setTimeout(() => {
        this.luyinType = true;
      }, 1000);

      // 设置一个计数器，从1开始每秒增加1，直到达到60秒
      let counter = 1;
      this.timer = setInterval(() => {
        console.log(counter++); // 输出计数器的当前值，然后递增
        if (counter > 60) {
          clearInterval(this.timer); // 如果计数器达到60秒，清除定时器
        }
      }, 1000); // 定时器每1000毫秒触发一次

      //新
      this.recorder.start();

      // return;
      this.intervalId = setInterval(async () => {
        var blob = this.recorder.getBlob();
        // 使用fetch API发送Blob数据
        // var blob2 = blob.slice(this.index, blob.size - 1, 'audio/wav');
        // this.index = blob.size - 1;
        //blob格式转换为base64格式
        this.blobToDataURI(blob, (result) => {
          this.errText.push("生成base64");
          let data = {
            data: result.split(",")[1],
          };
          this.resultBase64 = result.split(",")[1];
        });
      }, 1000);
    },
    surroundWordsWithQuotes(str) {
      // 正则表达式匹配一个或多个空格，并在单词前后添加双引号
      return str.replace(/\b\w+\b/g, (word) => `"${word}"`);
    },
    voiceNew() {
      var that = this;
      this.$nextTick(() => {
        try {
          // <!-- 检查是否能够调用麦克风 -->
          window.AudioContext = window.AudioContext || window.webkitAudioContext;
          navigator.mediaDevices.getUserMedia =
            navigator.mediaDevices.getUserMedia || navigator.webkitGetUserMedia;
          window.URL = window.URL || window.webkitURL;

          that.audio_context = new AudioContext();

          that.errText.push(
            `'navigator.mediaDevices.getUserMedia ' + (${navigator.mediaDevices.getUserMedia ? "available." : "not present!"
            })`
          );
          console.log(
            "navigator.mediaDevices.getUserMedia " +
            (navigator.mediaDevices.getUserMedia ? "available." : "not present!")
          );
        } catch (e) {
          alert("No web audio support in this browser!");
          that.errText.push("No web audio support in this browser!");
        }

        console.log(
          navigator.mediaDevices.getUserMedia,
          "navigator.mediaDevices.getUserMedia"
        );

        var constraints = { audio: true };
        navigator.mediaDevices
          .getUserMedia(constraints)
          .then(function (stream) {
            console.log(stream, "stream");
            that.recorder = new HZRecorder(stream, {
              sampleBits: 16,
              sampleRate: 8000,
            });
            console.log("初始化完成");
            that.errText.push("初始化完成");

            that.voiceType = !that.voiceType;
          })
          .catch(function (err) {
            console.log(err);
            that.errText.push(err + "");

            if (err.name == "NotFoundError" || err.name == "DeviceNotFoundError") {
              // require track is missing
            } else if (err.name == "NotReadableError" || err.name == "TrackStartError") {
              // webcam or mic are already in use
            } else if (
              err.name == "OverconstrainedError" ||
              err.name == "ConstraintNotSatisfiedError"
            ) {
              // constraints can not be satisfied by avb.device
            } else if (
              err.name == "NotAllowedError" ||
              err.name == "PermissionDeniedError"
            ) {
              // permission denied in browser
            } else if (err.name == "TypeError" || err.name == "TypeError") {
              // empty constraints object
            } else {
              // other errors
            }
          });
        return;
      });
    },

    copyText(index) {
      console.log(this.$refs["text" + index][0].innerText);

      var cInput = document.createElement("input");
      // cInput.value = this.resultData[index];
      cInput.value = this.$refs["text" + index][0].innerText;
      document.body.appendChild(cInput);
      cInput.select(); // 选取文本框内容

      document.execCommand("copy");

      this.$message({
        type: "success",
        center: true,
        message: "复制成功",
        offset: window.screen.height / 2,
      });
      // 复制成功后再将构造的标签 移除
      document.body.removeChild(cInput);
    },
    containsNewline(str) {
      return /\n|\r\n|\r/.test(str);
    },
    countWordOccurrences(str, word) {
      const regex = new RegExp(`\\b${word}\\b`, "g");
      return (str.match(regex) || []).length;
    },
    containsDoubleCurlyBraces(str) {
      return /}}/.test(str);
    },
    retract() {
      this.valueYuyin = "";
      this.startType = false;
      this.luyinType = false;
      this.endType = false;
    },
    sendInput(value) {
      if (value) {
        console.log("进入");
        this.value = value + "";
        this.retract();
      }
      if (!this.value) {
        this.$message({
          message: "请填写问题",
          center: true,
          type: "warning",
          offset: window.screen.height / 2,
        });
        return;
      } else if (this.resultType) {
        this.$message({
          message: "问题回答中",
          center: true,
          type: "info",
          offset: window.screen.height / 2,
        });
        return;
      }
      this.setExpireCookie("userCookie", this.userCookie, 15);
      this.resultType = true;
      let text = this.value;
      this.userData.push(text);
      this.copyChat.push(false);
      // this.question += 1;
      this.$set(this, "question", this.question + 1);
      this.resultData.push("");
      this.value = "";
      this.isScrollByTouch = true;
      this.$nextTick(() => {
        this.chatDom.scrollTop = this.chatDom.scrollHeight;
      });
      let url = "https://ai.oramage.com/v1/workflows/run"
      // let url = "https://api.coze.cn/v1/workflow/stream_run"

      fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          'authorization': 'Bearer app-mLeiYNTX1tassE7QxdZ1EwD7'
          // 'authorization': 'Bearer pat_BBSBBPVoVjsX51tH4Bo9L8zT7Q0O6buJ3MGajYmwgQhJ7CRbj7nDWrU4puoAuVAN'
        },
        // 传参只能发送文本格式的数据
        body: JSON.stringify({
          "inputs": {
            "url": `${PAGE_BASE_URL}/#/analysis?id=${this.$route.query.id}&AI=1`,
            "question": text
          },
          "user": "02e54e30-9f1d-4dec-bac0-8b967d8f0a7a",
          "response_mode": "streaming"
        }),

      })
        .then((response) => {
          if (!response.ok) {
            throw new Error("Network response was not ok");
          }
          console.log(response, "response");
          // 确保返回的内容类型是 "text/event-stream"
          const contentType = response.headers.get("content-type");
          if (!contentType || !contentType.includes("text/event-stream")) {
            throw new Error('Expected "text/event-stream" content-type');
          }
          // 将 Response 对象的 body 转换为 ReadableStream
          const readable = response.body.pipeThrough(new TextDecoderStream());

          // 处理流结束
          readable.pipeTo(
            new WritableStream({
              write: (chunk) => {
                let type = this.countWordOccurrences(chunk, "answer") == 1 ? true : false;
                type = true;
                var regex = new RegExp("data:");
                let newData = chunk.replace(regex, "");
                regex = new RegExp("event: ping");
                newData = newData.replace(regex, "");
                console.log(newData);

                let datajson;

                if (type) {
                  try {
                    if (this.stopType) {
                      console.log(nonExistentVariable);
                    }
                  } catch (e) {
                    this.stopType = false;
                    this.isScrollByTouch = false;
                    this.thinkload = "";
                    this.resultload = "";
                    this.resultType = false;
                    this.$set(this.copyChat, this.question - 1, true);
                    throw "中断";
                  }
                  try {
                    datajson = JSON.parse(newData);
                    console.log(JSON.parse(newData), "对象");
                    let md = new MarkdownIt()

                    if (type && datajson.data.text) {
                      if (datajson.data.text.indexOf("<think>") >= 0) {
                        this.resultType2 = true;
                        let parts = datajson.data.text.split("<think>")[1]; // 分割出"start"之前的部分
                        this.thinkload += parts;
                        let html = md.render(this.thinkload)
                        this.$set(this.thinkData, this.question - 1, html);
                      } else if (datajson.data.text.indexOf("</think>") >= 0) {
                        this.resultType2 = false;
                        let parts = datajson.data.text.split("</think>"); // 分割出"start"之前的部分
                        this.thinkload += parts[0];
                        let html = md.render(
                          this.thinkload
                        )
                        this.$set(this.thinkData, this.question - 1, html);

                        this.resultload += parts[1];
                        let html2 = md.render(
                          this.resultload
                        )
                        this.$set(this.resultData, this.question - 1, html2);
                      } else if (this.resultType2) {
                        let parts = datajson.data.text; // 分割出"start"之前的部分
                        this.thinkload += parts;
                        let html = md.render(
                          this.thinkload
                        )
                        this.$set(this.thinkData, this.question - 1, html);
                      } else {
                        this.resultload += datajson.data.text;
                        let html = md.render(
                          this.resultload
                        )
                        this.$set(this.resultData, this.question - 1, html);
                      }
                    }else if(datajson.event == 'workflow_finished'){
                      let data  = datajson.data.outputs.content.split("</think>");
                      if(data){
                        let html =  md.render(data[1])
                        this.$set(this.resultData, this.question - 1, html);

                        let html2 = md.render(data[0].split("<think>")[1])
                        this.$set(this.thinkData, this.question - 1, html2);

                      }
                    }
                  } catch (e) {

                  }
                }
              },
              close: async () => {
                this.isScrollByTouch = false;
                this.thinkload = "";
                this.resultload = "";
                this.resultType = false;
                this.$set(this.copyChat, this.question - 1, true);
                console.log("Stream closed");

                if (
                  this.userData[this.question - 1] &&
                  this.resultData[this.question - 1]
                ) {
                  const response = await axios.post(
                    "https://test.ai.oramage.com/web.php/chat/saveMessage",
                    {
                      user_token: this.userCookie,
                      question: this.userData[this.question - 1],
                      message: this.resultData[this.question - 1],
                    }
                  );
                }

                console.log(response.data, "response");

                this.$nextTick(() => {
                  this.chatDom.scrollTop = this.chatDom.scrollHeight;
                });
              },
              abort: (err) => {
                this.stopType = false;
                this.isScrollByTouch = false;
                this.thinkload = "";
                this.resultload = "";
                this.resultType = false;
                this.$set(this.copyChat, this.question - 1, true);
                console.log("Sink error:", err);
              },
            })
          );
        })
        .catch((error) => {
          console.error("Fetch or EventSource error:", error);
        });
    },
  },
};
</script>

<style scoped lang="less">
.zzc {
  z-index: 9;
  position: fixed;
  right: 0;
  top: 0;
  width: 480px;
  height: 100%;
  opacity: 0.5;
  background: #000;
}

.mdTextBox {
  width: 1400px;
}

::v-deep .el-dialog {
  border-radius: 10px;
}

.dialogAI {
  .ConsultItem {
    cursor: pointer;
    padding: 14px;
    background-color: #fff;
    border: 1px solid #dadada;
    border-radius: 10px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: all 0.21s;
  }

  ::v-deep .el-dialog {
    margin: 0 40px 0 auto;
  }

  .ConsultItem:hover {
    background-color: #f4f6ff;
  }

  .areaClick {
    font-size: 20px;
    line-height: initial;
    text-align: center;

    .nickname {
      margin: 10px 0;
    }

    .btn {
      display: inline-block;
      border: 1px solid #f68b4e;
      padding: 5px;
      border-radius: 10px;
      margin-top: 10px;
      background-color: #f68b4e;
      color: #fff;
    }
  }

  .text {
    text-align: center;
    font-size: 16px;
    line-height: initial;

    .phone {
      font-size: 18px;
      font-weight: bold;
      margin: 5px 0;
      display: inline-block;
    }
  }

  .area {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;

    .areaitem {
      border-radius: 10px;
      border: 1px solid #dadada;
      padding: 10px;
      margin-bottom: 10px;
      background-color: #fff;
      transition: all 0.21s;
      cursor: pointer;
      margin: 0 9px 10px;
    }

    .areaitem:hover {
      background-color: #f4f6ff;
    }
  }
}

.head {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 44px;
  font-size: 16px;
  font-weight: bold;
  background-color: #edf0f7;
}

::v-deep .content {
  background: #fefaf8;

  .chat {
    line-height: initial;
    height: calc(100vh - 46px);
    padding: 10px 20px 0 20px;
    overflow: scroll;
    overflow-x: hidden;
    overflow-y: auto;
    padding-bottom: 10px;
    // -webkit-user-select: none;
    // /* Safari */
    // -moz-user-select: none;
    // /* Firefox */
    // -ms-user-select: none;
    // /* IE/Edge */
    // user-select: none;
    /* 标准语法 */
    margin: initial;
  }

  .AIBox {
    .wenben {
      .think {
        background-color: #eef0f6;
        margin: 10px 0 0px 0;
        border-radius: 0 10px 10px 10px;
        padding: 10px 20px;
      }

      .text {
        background-color: #fff;
        margin: 10px 0 20px 0;
        border-radius: 0 10px 10px 10px;
        padding: 10px 20px;

        span>* {
          margin-bottom: 10px;
          // white-space: pre-wrap;
        }

        span>*>* {
          margin-bottom: 10px;
        }

        img {
          width: 100%;
        }

        .copy {
          padding: 5px 8px;
          width: 60px;
          border: 1px solid #f68b4e;
          color: #f68b4e !important;
          border-radius: 30px;
          color: #6f6c6c;
          margin-top: 10px;
          text-align: center;
        }

        .operate {
          display: flex;
          justify-content: space-between;

          .like {
            display: flex;

            .likeItem {
              border: 1px solid #9a9a9a;
              display: flex;
              align-items: center;
              border-radius: 30px;
              margin-right: 5px;
              margin-top: 10px;
              color: #9a9a9a;
              padding: 0px 8px;
            }

            .activation {
              border: 1px solid #f68b4e;
              color: #f68b4e !important;
            }
          }
        }
      }

      .userBox {
        display: flex;
        justify-content: flex-end;

        .text {
          background-color: #346bfc;
          margin: 10px 0 20px 0;
          border-radius: 10px 10px 0 10px;
          padding: 10px 20px;
          color: #fff;
          margin-left: 40px;
        }
      }
    }
  }

  .question {
    padding: 20px 0;

    .questionItem {

      &:hover {
        background-color: #f2f3f8;
      }

      padding: 5px 10px;
      background-color: #fff;
      border: 1px solid #dadada;
      border-radius: 10px;
      margin-bottom: 10px;
      // display: flex;
      // justify-content: space-between;
      // align-items: center;
      font-size: 15px;
      display: inline-block;
      cursor: pointer;

      .title {
        // font-weight: bold;
      }

      .el-icon-caret-right {
        font-size: 24px;
      }

      .text {
        color: #989898;
        margin-top: 5px;
      }
    }

  }
}

pre {
  white-space: normal;
}

code {
  white-space: normal;
}

::v-deep pre {
  white-space: normal;
}

::v-deep code {
  white-space: normal;
}

::v-deep pre {
  white-space: normal;
}

::v-deep code {
  white-space: normal;
}

.yuyinBgc {
  position: fixed;
  bottom: 0;
  right: -10%;
  left: -10%;
  height: 300px;
  background-color: rgba(52, 107, 252, 0.9);
  border-radius: 100%;
  transform: translateY(50%);
  // box-shadow: 0px 0px 10000px 300px rgba(52, 107, 252, 0.35);
  box-shadow: 0px 0px 10000px 3000px rgba(30, 30, 30, 0.85);
  z-index: 99;
  -webkit-user-select: none;
  /* Safari */
  -moz-user-select: none;
  /* Firefox */
  -ms-user-select: none;
  /* IE/Edge */
  user-select: none;
  /* 标准语法 */

  .icon {
    position: absolute;
    left: 15%;
    right: 15%;
    bottom: 65%;
    text-align: center;
    font-size: 24px;
    color: #fff;
  }

  ::v-deep .input {
    position: absolute;
    left: 15%;
    right: 15%;
    bottom: 100%;

    .el-textarea__inner {
      background-color: rgba(255, 255, 255, 0);
      border: none;
      font-size: 24px;
      color: #fff;
    }
  }

  .cancellation {
    position: absolute;
    background-color: #fff;
    width: 70px;
    height: 70px;
    border-radius: 50%;
    left: 10%;
    bottom: 60%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .ack {
    position: absolute;
    background-color: #fff;
    color: #95ec6a;
    font-weight: bold;
    width: 70px;
    height: 70px;
    border-radius: 50%;
    right: 10%;
    bottom: 60%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.textInput {
  background-color: #fff;
  height: 45px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  border-radius: 50px;
  position: absolute;
  bottom: 35px;
  left: 20px;
  right: 20px;
  box-shadow: 0px 0px 20px 0px rgba(0, 0, 0, 0.2);

  ::v-deep .el-input__inner {
    border: none;
    padding: 0;
  }

  .voiceType {
    flex: 1 1 0%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    user-select: none;
  }

  .icon {
    font-size: 18px;
    width: 45px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .iconText {
    font-size: 16px;
    // width: 78px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #777575;
  }
}

.resultText {
  color: #fff;
  background: #346bfc;
  padding: 8px 12px;
  border-radius: 30px;
  max-width: 60px;
}

@media (max-width: 750px) {
  .dialogAI {
    ::v-deep .el-dialog {
      margin: 0 auto;
    }

    .area {
      justify-content: space-between;
    }
  }
}
</style>
